package it.uniba.di.mas.jpnde.behaviour;

import it.uniba.di.mas.jpnde.core.IDeliverable;
import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.SequentialBehaviour;
import jade.lang.acl.ACLMessage;
import jade.proto.AchieveREInitiator;


public class PNManagerDelivery extends AchieveREInitiator{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public static final short CREATE_AGENT=0;
	public static final short SEND_DELIVERY=1;
	
	private SequentialBehaviour composite=null;
	private IDeliverable delivery=null;
	private String agentId=null;
	private short step=CREATE_AGENT;
	
	public PNManagerDelivery(SequentialBehaviour composite, 
			Agent a, ACLMessage msg, 
			IDeliverable delivery,String agentId) {
		super(a, msg);
		// TODO Auto-generated constructor stub
		this.composite=composite;
		this.delivery=delivery;
		this.agentId=agentId;
	}
	
	public PNManagerDelivery(SequentialBehaviour composite, 
			Agent a, ACLMessage msg, 
			IDeliverable delivery,String agentId, short step) {
		super(a, msg);
		// TODO Auto-generated constructor stub
	
		this.composite=composite;
		this.step=step;
		this.delivery=delivery;
		this.agentId=agentId;

	}
	
	protected void handleInform(ACLMessage inform)
	{
		System.out.println("PNManagerDelivery.handleInform():"+delivery.getId()+" - "+step);
		switch(step){
		case CREATE_AGENT:
	    	ACLMessage message=new ACLMessage(ACLMessage.REQUEST);
			message.addReceiver(new AID(agentId,AID.ISLOCALNAME));
			try {
				message.setContentObject(delivery);
				composite.addSubBehaviour(new PNManagerDelivery(composite,myAgent,
						message,delivery,agentId,SEND_DELIVERY));
				}
			catch(Exception e)
				{
				e.printStackTrace();
				}
	 		break;
		case SEND_DELIVERY:
			delivery.setAgentId(inform.getSender().getName());
			break;
		}
	}
	
	protected void handleFailure(ACLMessage inform)
	{
		System.out.println("PNManagerDelivery.handleFailure():"+delivery.getId()+" - "+step);
	}
	
}
